<template>
  <div class="app-container" :key="`${operationType}-${columnId || 'new'}`">
    <div slot="header" class="clearfix">
      <span class="card-title">{{ title }}</span>
      <div class="card-actions">
        <el-button @click="goBack" icon="el-icon-back">返回</el-button>
      </div>
    </div>
      
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="24" v-if="form.parentId !== 0">
            <el-form-item label="上级栏目" prop="parentId">
              <treeselect v-model="form.parentId" :options="columnOptions" :normalizer="normalizer"
                placeholder="选择上级栏目" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="栏目名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入栏目名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示排序" prop="orderNum">
              <el-input-number v-model="form.orderNum" controls-position="right" :min="0" placeholder="排序" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="角色" prop="role">
              <el-input v-model="form.role" placeholder="请输入角色" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示状态">
              <el-radio-group v-model="form.status">
                <el-radio :label="1">显示</el-radio>
                <el-radio :label="0">隐藏</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="选中图片" prop="img1">
              <el-upload
                ref="img1Upload"
                :file-list="img1FileList"
                :before-upload="beforeImg1Upload"
                :on-change="handleImg1FileChange"
                :auto-upload="false"
                :on-remove="handleImg1Remove"
                :limit="1"
                list-type="picture-card"
                accept="image/*"
                action="#"
                :http-request="handleImg1HttpRequest"
              >
                <i class="el-icon-plus"></i>
                <div slot="tip" class="el-upload__tip">请上传选中状态图片</div>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="未选中图片" prop="img2">
              <el-upload
                ref="img2Upload"
                :file-list="img2FileList"
                :before-upload="beforeImg2Upload"
                :on-change="handleImg2FileChange"
                :auto-upload="false"
                :on-remove="handleImg2Remove"
                :limit="1"
                list-type="picture-card"
                accept="image/*"
                action="#"
                :http-request="handleImg2HttpRequest"
              >
                <i class="el-icon-plus"></i>
                <div slot="tip" class="el-upload__tip">请上传未选中状态图片</div>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      
      <div class="form-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="goBack">取 消</el-button>
      </div>
  </div>
</template>

<script>
import { listConlumn, getConlumn, delConlumn, addConlumn, updateConlumn, mobileColumns } from "@/api/conlumn/column-content.js";
import { uploadFile } from "@/api/article/article";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "ConlumnForm",
  components: { Treeselect },
  data() {
    return {
      // 页面标题
      title: "",
      // 操作类型：add, edit
      operationType: "",
      // 栏目ID（编辑时使用）
      columnId: null,
      // 是否显示弹出层
      open: true,
      
      // 栏目树选项
      columnOptions: [],
      
      // 表单参数
      form: {},
      
      // 图片上传相关
      img1FileList: [],
      img2FileList: [],
      uploadImg1File: null,
      uploadImg2File: null,
      
      // 暂存文件（用于新增时）
      tempImg1File: null,
      tempImg2File: null,
      
      // 表单校验
      rules: {
        name: [
          { required: true, message: "栏目名称不能为空", trigger: "blur" }
        ],
        orderNum: [
          { required: true, message: "显示排序不能为空", trigger: "blur" }
        ],
      }
    };
  },
  mounted() {
    this.initPage();
  },
  watch: {
    // 监听路由参数变化
    '$route.query': {
      handler(newQuery, oldQuery) {
        // 当路由参数变化时，重新初始化页面
        if (newQuery.operationType !== oldQuery.operationType || newQuery.id !== oldQuery.id) {
          this.initPage();
        }
      },
      deep: true,
      immediate: false
    }
  },
  methods: {
    // 初始化页面
    initPage() {
      // 先清空所有数据状态
      this.reset();
      
      this.getColumnList();
      
      // 获取路由参数
      const { operationType, id, parentId } = this.$route.query;
      this.operationType = operationType || 'add';
      this.columnId = id ? parseInt(id) : null;
      
      // 设置页面标题
      this.setPageTitle();
      
      // 如果是编辑模式，加载数据
      if (this.operationType === 'edit' && this.columnId) {
        this.loadColumnData();
      } else {
        // 如果是新增模式且有父级ID，设置父级栏目
        if (parentId) {
          this.form.parentId = parseInt(parentId);
        }
      }
      
      // 重新初始化表单
      this.$nextTick(() => {
        this.initForm();
      });
    },
    
    // 初始化表单
    initForm() {
      // 清空表单验证状态
      if (this.$refs.form) {
        this.$refs.form.clearValidate();
      }
      
      // 强制重新渲染表单组件
      this.$forceUpdate();
      
      // 确保树形选择器重新渲染
      this.$nextTick(() => {
        if (this.$refs.treeselect) {
          this.$refs.treeselect.$forceUpdate();
        }
      });
    },
    
    // 设置页面标题
    setPageTitle() {
      switch (this.operationType) {
        case 'add':
          this.title = '新增栏目';
          break;
        case 'edit':
          this.title = '修改栏目';
          break;
        default:
          this.title = '栏目管理';
      }
    },
    
    // 查询栏目列表
    getColumnList() {
      const queryParams = {
        pageNum: 1,
        pageSize: 1000,
        name: null,
        role: null
      };
      
      listConlumn(queryParams).then(response => {
        this.columnOptions = this.handleTree(response.data, "id", "parentId", "children");
      });
    },
    
    // 加载栏目数据
    loadColumnData() {
      getConlumn(this.columnId).then(response => {
        this.form = response.data || response;
        
        // 初始化图片文件列表
        if (this.form.img1) {
          this.img1FileList = [{
            name: "选中图片",
            url: this.form.img1
          }];
        } else {
          this.img1FileList = [];
        }
        
        if (this.form.img2) {
          this.img2FileList = [{
            name: "未选中图片",
            url: this.form.img2
          }];
        } else {
          this.img2FileList = [];
        }
      });
    },
    
    // 重置表单
    reset() {
      this.form = {
        id: null,
        parentId: 0,
        name: null,
        orderNum: 0,
        role: null,
        status: 1,
        img1: null,
        img2: null
      };
      
      // 清空图片上传相关数据
      this.img1FileList = [];
      this.img2FileList = [];
      this.uploadImg1File = null;
      this.uploadImg2File = null;
      
      // 清空暂存文件
      this.tempImg1File = null;
      this.tempImg2File = null;
      
      this.resetForm("form");
    },
    
    // 返回上一页
    goBack() {
      this.$router.go(-1);
    },
    
    // 提交表单
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.operationType === 'add') {
            this.handleAdd();
          } else if (this.operationType === 'edit') {
            this.handleUpdate();
          }
        }
      });
    },
    
    // 新增栏目
    async handleAdd() {
      try {
        // 先提交表单，获取栏目ID
        const response = await addConlumn(this.form);
        if (response.code === 200) {
          // 获取新创建的栏目ID
          const newColumnId = response.data?.id || response.data?.columnId;
          
          // 如果有暂存的选中图片，现在上传
          if (this.tempImg1File && newColumnId) {
            try {
              await this.uploadImg1AfterCreate(newColumnId);
            } catch (uploadError) {
              console.warn('选中图片上传失败，但栏目已创建成功:', uploadError);
              this.$message.warning('栏目创建成功，但选中图片上传失败，请稍后手动上传');
            }
          }
          
          // 如果有暂存的未选中图片，现在上传
          if (this.tempImg2File && newColumnId) {
            try {
              await this.uploadImg2AfterCreate(newColumnId);
            } catch (uploadError) {
              console.warn('未选中图片上传失败，但栏目已创建成功:', uploadError);
              this.$message.warning('栏目创建成功，但未选中图片上传失败，请稍后手动上传');
            }
          }
          
          this.$modal.msgSuccess("新增成功");
          // 清空表单数据状态
          this.reset();
          this.goBack();
        } else {
          this.$modal.msgError(response.msg || "新增失败");
        }
      } catch (error) {
        console.error('新增栏目失败:', error);
        this.$modal.msgError('新增失败: ' + (error.message || '未知错误'));
      }
    },
    
    // 修改栏目
    async handleUpdate() {
      try {
        // 处理文件上传
        await this.handleFileUploads();
        
        const response = await updateConlumn(this.form);
        if (response.code === 200) {
          this.$modal.msgSuccess("修改成功");
          this.goBack();
        } else {
          this.$modal.msgError(response.msg || "修改失败");
        }
      } catch (error) {
        console.error('修改栏目失败:', error);
        this.$modal.msgError('修改失败: ' + (error.message || '未知错误'));
      }
    },
    
    // 处理树形数据
    handleTree(data, id, parentId, children) {
      const cloneData = JSON.parse(JSON.stringify(data));
      const tree = [];
      const map = {};
      
      cloneData.forEach(item => {
        map[item[id]] = item;
      });
      
      cloneData.forEach(item => {
        const parent = map[item[parentId]];
        if (parent) {
          (parent[children] || (parent[children] = [])).push(item);
        } else {
          tree.push(item);
        }
      });
      
      return tree;
    },
    
    // 树形选择器配置
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children
      };
    },
    
    // 处理文件上传
    async handleFileUploads() {
      // 处理选中图片上传
      if (this.uploadImg1File) {
        await this.uploadImg1ToServer(this.uploadImg1File);
      }
      
      // 处理未选中图片上传
      if (this.uploadImg2File) {
        await this.uploadImg2ToServer(this.uploadImg2File);
      }
    },
    
    // 选中图片上传前处理
    beforeImg1Upload(file) {
      const isImage = file.type.startsWith('image/');
      if (!isImage) {
        this.$message.error('只能上传图片文件!');
        return false;
      }
      
      // 如果是新增模式，暂存文件
      if (this.operationType === 'add') {
        this.tempImg1File = file;
        this.$message.info('选中图片已选择，将在栏目创建后上传');
      } else {
        this.uploadImg1File = file;
      }
      return false;
    },
    
    // 选中图片文件变化处理
    handleImg1FileChange(file, fileList) {
      if (fileList.length > 0) {
        this.uploadImg1File = fileList[fileList.length - 1].raw;
        this.img1FileList = [fileList[fileList.length - 1]];
      } else {
        this.uploadImg1File = null;
        this.img1FileList = [];
      }
    },
    
    // 选中图片文件移除处理
    handleImg1Remove(file, fileList) {
      this.uploadImg1File = null;
      this.img1FileList = [];
    },
    
    // 选中图片上传请求处理
    handleImg1HttpRequest(options) {
      this.uploadImg1ToServer(options.file);
    },
    
    // 上传选中图片到服务器
    async uploadImg1ToServer(file) {
      try {
        const formData = new FormData();
        formData.append('file', file);
        
        const response = await uploadFile(formData);
        if (response.code === 200) {
          this.form.img1 = response.url;
          this.$message.success('选中图片上传成功');
        } else {
          throw new Error(response.msg || '上传失败');
        }
      } catch (error) {
        console.error('选中图片上传失败:', error);
        this.$message.error('选中图片上传失败: ' + error.message);
        throw error;
      }
    },
    
    // 未选中图片上传前处理
    beforeImg2Upload(file) {
      const isImage = file.type.startsWith('image/');
      if (!isImage) {
        this.$message.error('只能上传图片文件!');
        return false;
      }
      
      // 如果是新增模式，暂存文件
      if (this.operationType === 'add') {
        this.tempImg2File = file;
        this.$message.info('未选中图片已选择，将在栏目创建后上传');
      } else {
        this.uploadImg2File = file;
      }
      return false;
    },
    
    // 未选中图片文件变化处理
    handleImg2FileChange(file, fileList) {
      if (fileList.length > 0) {
        this.uploadImg2File = fileList[fileList.length - 1].raw;
        this.img2FileList = [fileList[fileList.length - 1]];
      } else {
        this.uploadImg2File = null;
        this.img2FileList = [];
      }
    },
    
    // 未选中图片文件移除处理
    handleImg2Remove(file, fileList) {
      this.uploadImg2File = null;
      this.img2FileList = [];
    },
    
    // 未选中图片上传请求处理
    handleImg2HttpRequest(options) {
      this.uploadImg2ToServer(options.file);
    },
    
    // 上传未选中图片到服务器
    async uploadImg2ToServer(file) {
      try {
        const formData = new FormData();
        formData.append('file', file);
        
        const response = await uploadFile(formData);
        if (response.code === 200) {
          this.form.img2 = response.url;
          this.$message.success('未选中图片上传成功');
        } else {
          throw new Error(response.msg || '上传失败');
        }
      } catch (error) {
        console.error('未选中图片上传失败:', error);
        this.$message.error('未选中图片上传失败: ' + error.message);
        throw error;
      }
    },
    
    // 新增后上传选中图片
    async uploadImg1AfterCreate(columnId) {
      if (!this.tempImg1File) return;
      
      try {
        const formData = new FormData();
        formData.append('file', this.tempImg1File);
        
        const response = await uploadFile(formData);
        if (response.code === 200) {
          // 更新栏目的选中图片路径
          await updateConlumn({
            id: columnId,
            img1: response.url
          });
          this.$message.success('选中图片上传成功');
        }
      } catch (error) {
        console.error('新增后选中图片上传失败:', error);
        throw error;
      }
    },
    
    // 新增后上传未选中图片
    async uploadImg2AfterCreate(columnId) {
      if (!this.tempImg2File) return;
      
      try {
        const formData = new FormData();
        formData.append('file', this.tempImg2File);
        
        const response = await uploadFile(formData);
        if (response.code === 200) {
          // 更新栏目的未选中图片路径
          await updateConlumn({
            id: columnId,
            img2: response.url
          });
          this.$message.success('未选中图片上传成功');
        }
      } catch (error) {
        console.error('新增后未选中图片上传失败:', error);
        throw error;
      }
    }
  }
};
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.box-card {
  margin-bottom: 20px;
}

.card-title {
  font-size: 18px;
  font-weight: bold;
}

.card-actions {
  float: right;
}

.clearfix:after {
  content: "";
  display: table;
  clear: both;
}

.form-footer {
  text-align: center;
  padding: 20px 0;
  border-top: 1px solid #e4e7ed;
  margin-top: 20px;
}
</style>
